package cn.wolfcode.trip.base.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具
 */
public class UploadUtil {
    // 图片服务器的文件夹路径
    public static final String IMAGE_PATH = "D:\\Super520\\tomcat-image\\webapps\\ROOT\\upload";
    public static final String IMAGE_DOMAIN = "http://192.168.14.133:5555";
    //七牛云服务器uii
    public static final String QINIU_IMAGES_DOMAIN = "http://prqg478jl.bkt.clouddn.com/";

    /**
     * 处理文件上传
     *
     * @param file
     * @return 123.png
     */
    public static String upload(MultipartFile file) {
        String uuid = UUID.randomUUID().toString(); // 随机字符串

        String orgFileName = file.getOriginalFilename(); // 获取文件名称 xxx.jpg
        String ext = "." + FilenameUtils.getExtension(orgFileName); // 返回后缀名 .jpg
        String fileName = uuid + ext;        // 随机字符串组成新的文件名
        try {
            File targetFile = new File(IMAGE_PATH, fileName);    // 图片服务器地址
            FileUtils.writeByteArrayToFile(targetFile, file.getBytes()); // 写入文件数据
            return IMAGE_DOMAIN + "/upload/" + fileName; // 返回文件的http地址
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 七牛云图片上传
     * @param file
     * @return
     */
    public static String uploadQiniu(MultipartFile file){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "yUPFI7s9XtHmhnMW7FiQhiqr7A_JSc3UyeuZZ4Ap";
        String secretKey = "jdRT9J3rzjzFNcnO0aW8y2lODaH05S77bxhzKmBU";
        String bucket = "newimg";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return QINIU_IMAGES_DOMAIN+putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
























